package testpackage;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.rmi.RemoteException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import NET.webserviceX.www.Currency;
import NET.webserviceX.www.CurrencyConvertorSoapProxy;

/**
 * Servlet implementation class CurrencyConvertorClient
 */
public class IntegratedApp extends HttpServlet {
	private static final long serialVersionUID = 1L;
	   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public IntegratedApp() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		performTask(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		performTask(request, response);
	}
	
	private void performTask(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action = "";
		if(request.getParameter("action") == null){
			System.err.println("--- performTask: no action parameter specified!");
			action = "";
		}else{
			action = request.getParameter("action").toString();
		}
		System.out.println("--- starting IntegratedApp ---");
		System.out.println("\n--- action: "+action);
		
		if (action.equalsIgnoreCase("getCars")){
			PrintWriter writer = response.getWriter();
			String fileLine = "";
			try {
				BufferedReader in = new BufferedReader(new FileReader(new File("/Users/fil/Documents/workspace_j2ee/HelloWorld/src/testpackage/cars.txt")));
				while ((fileLine = in.readLine()) != null) {
					System.out.println(fileLine);
					writer.write(fileLine);
				}
			} catch(Exception e){
				e.printStackTrace();
			}
			writer.flush();
			writer.close();
		}else if (action.equalsIgnoreCase("getRatio")){
			PrintWriter writer = response.getWriter();
			String targetCurrency = "EUR"; //default value

			if(request.getParameter("targetCurrency") != null){
				targetCurrency = String.valueOf(request.getParameter("targetCurrency"));
				System.out.println("got parameter targetCurrency: "+targetCurrency);
			}
			writer.println(getCurrencyRatio(targetCurrency));
			writer.flush();
			writer.close();

		}else if (action.equalsIgnoreCase("rentCar")){
			String fileLine = "";
			ArrayList<String> contentList = new ArrayList<String>();
			int carID = 0;
			if(request.getParameter("carID") != null){
				carID = Integer.valueOf(request.getParameter("carID"));
				System.out.println("got parameter carID: "+carID);
			}
			
			try {
				BufferedReader in = new BufferedReader(new FileReader(new File("/Users/fil/Documents/workspace_j2ee/HelloWorld/src/testpackage/cars.txt")));
				for(int i = 0; (fileLine = in.readLine()) != null; i++) {
					contentList.add(i, fileLine+"\n");
				}
			} catch(Exception e){
				e.printStackTrace();
			}
			try {
				//write the modified text back
				String[] foo = ArrayListToString(contentList).split(";");
				foo[4*carID+2]="B";
				String contentString = "";
				for( int i = 0; i < foo.length; i++){
					contentString += foo[i];
					if ( i < foo.length-1 ){
						contentString += ";";
					}
				}
				BufferedWriter out = new BufferedWriter(new FileWriter("/Users/fil/Documents/workspace_j2ee/HelloWorld/src/testpackage/cars.txt"));
				System.out.println("Writing contentString to file:\n"+contentString);
				out.write(contentString);
				out.flush();
				out.close();
				System.out.println("file saved.");
			} catch(Exception e){
				e.printStackTrace();
			}

		}else if (action.equalsIgnoreCase("returnCar")){
			String fileLine = "";
			ArrayList<String> contentList = new ArrayList<String>();
			int carID = 0;
			if(request.getParameter("carID") != null){
				carID = Integer.valueOf(request.getParameter("carID"));
				System.out.println("got parameter carID: "+carID);
			}
			
			try {
				BufferedReader in = new BufferedReader(new FileReader(new File("/Users/fil/Documents/workspace_j2ee/HelloWorld/src/testpackage/cars.txt")));
				for(int i = 0; (fileLine = in.readLine()) != null; i++) {
					contentList.add(i, fileLine+"\n");
				}
			} catch(Exception e){
				e.printStackTrace();
			}
			try {
				//write the modified text back
				String[] foo = ArrayListToString(contentList).split(";");
				foo[4*carID+2]="A";
				String contentString = "";
				for( int i = 0; i < foo.length; i++){
					contentString += foo[i];
					if ( i < foo.length-1 ){
						contentString += ";";
					}
				}
				BufferedWriter out = new BufferedWriter(new FileWriter("/Users/fil/Documents/workspace_j2ee/HelloWorld/src/testpackage/cars.txt"));
				System.out.println("Writing contentString to file:\n"+contentString);
				out.write(contentString);
				out.flush();
				out.close();
				System.out.println("file saved.");
			} catch(Exception e){
				e.printStackTrace();
			}

		}else if(action.equalsIgnoreCase("showTraffic")){
			String trafficUrl = "#";
			int s = 0;

			if(request.getParameter("trafficUrl") != null){
				trafficUrl = request.getParameter("trafficUrl").toString();
			}

			PrintWriter writer = response.getWriter();
			writer.println("<table id=\"trafficTable\">");
	        try {
	        	Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(trafficUrl); // this line does lots of magic and little voodoo too
	        	doc.getDocumentElement().normalize();
				NodeList nodeList = doc.getElementsByTagName("Result");
	        	// iterate through the <Result>s
	        	for (s = 0; s < nodeList.getLength(); s++) {
	        		Node fstNode = nodeList.item(s);
	        		if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
	        			writer.println("<tr><td width=\"315\"><img src=\""+((Element)fstNode).getElementsByTagName("ImageUrl").item(0).getChildNodes().item(0).getNodeValue()+"\"></td>");
	        			writer.println("<td><strong>Report #"+(s+1)+":</strong> "+((Element)fstNode).getElementsByTagName("Title").item(0).getChildNodes().item(0).getNodeValue());
	        			writer.println("<br><strong>Description:</strong> "+((Element)fstNode).getElementsByTagName("Description").item(0).getChildNodes().item(0).getNodeValue()+"</td></tr>");
	        		}
	        	}
	        } catch (Exception e) {
	        	writer.println("<tr><td><br>Derzeit sind keine Verkehrs-Informationen verf&uuml;gbar, bitte versuchen Sie es zu einem sp&auml;teren Zeitpunkt erneut.</td></tr>");
	    	    e.printStackTrace();
	    	    s++;
	    	}
	        if(s == 0){
	        	writer.println("<tr><td><br>F&uuml;r diese Stadt sind keine Verkehrs-Informationen vorhanden.</td></tr>");
	        }
	        writer.println("</table>");
			writer.flush();
	    	writer.close();
		}else{
			PrintWriter writer = response.getWriter();	
	    	writer.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
			writer.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
			writer.println("<head>");
			writer.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");
			writer.println("<title>Autoverleih Campus Wien ITS11</title>");
			writer.println("</head>");
			writer.println("<body>");
			writer.println("missing action parameter");
			writer.println("</body>");
			writer.println("</html>");
			writer.flush();
	    	writer.close();
		}
	}
	
	private double getCurrencyRatio(String targetCurrency){
		System.out.println("--- starting IntegratedApp:getCurrencyRatio() ---");
		double ratio = 1;
		try{
			ratio = new CurrencyConvertorSoapProxy().conversionRate(Currency.EUR, Currency.fromValue(targetCurrency));
			System.out.println("Ratio (EUR-"+targetCurrency+") = "+ratio);
		} catch (RemoteException re) {
			System.out.println("\nProblem occured while Currency Conversion (probalby conversionRate())\n");
			re.printStackTrace();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return ((double)Math.round(ratio*100.0))/100.0;
	}
	
	private String ArrayListToString(ArrayList<String> al){
		String alString = "";
		for(int i = 0; i < al.size(); i++){
			alString += al.get(i);
		}
		return alString;
	}
}